<template>
  <div class="computer flex-col fill">
    <div class="head flex-row items-center pnx mnt">
      <i @click="handleBackClick" class="el-icon-back pnr" :class="{deActive: pathArray.length===1}"
         style="font-size: 20px"/>
      <div class="address-area flex-auto flex-row">
        <div @click="handlePathItemClick(index)" class="path-item flex-row items-center"
             v-for="(item, index) in pathArray" :key="item.id">
          <WIcon :icon="item.icon" :size="15"/>
          <span class="name msl">{{ item.name }}</span>
          <WIcon icon="icon-icon-right"/>
        </div>
      </div>
    </div>
    <div class="files-area flex-1 flex-row flex-wrap content-start" ref="files" @click.right="handleContextFilesArea">
      <div @dblclick="handleFileClick(file)" @click.right="handleContextFileItem($event, file)"
           class="file-item flex-col items-center" v-for="file in fileList"
           :key="file.id">
        <WIcon :icon="file.icon" :size="40"/>
        <div class="name">{{ file.name }}</div>
      </div>
    </div>
    <el-dialog :visible.sync="dialogVisible" width="500px" title="上传图片" append-to-body>
      <UploadImg @success="processUploadSuccess"/>
    </el-dialog>
    <el-dialog :visible.sync="album.visible" title="新增专辑" append-to-body>
      <el-form label-width="80px" label-position="right">
        <el-form-item label="名称">
          <el-input v-model="album.form.name"/>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="album.form.author"/>
        </el-form-item>
        <el-form-item label="图片">
          <el-button>上传</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="handleAlbumCreate">创建</el-button>
        <el-button @click="handleAlbumCancel">取消</el-button>
      </template>
    </el-dialog>
    <el-dialog :visible.sync="audio.visible" title="歌曲" append-to-body>
      <el-form label-width="80px" label-position="right">
        <el-form-item label="名称">
          <el-input v-model="audio.form.name"/>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="audio.form.author"/>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="audio.form.content"/>
        </el-form-item>
        <el-form-item label="图片">
          <el-button>上传</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="handleAudioCreate">创建</el-button>
        <el-button @click="audio.visible=false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script>
import {fileApi} from "@/api/table/file"
import WIcon from "@/components/icon/WIcon"
import {isDef} from "@/utils/jsUtils"
import UploadImg from "@/components/uploadImg/UploadImg"

export default {
  name: "Computer",
  components: {UploadImg, WIcon},
  data: () => ({
    pathArray: [
      {label: "此电脑", icon: "icon-diannao", id: 0, name: "此电脑"}
    ],
    fileList: [],
    dialogVisible: false,
    album: {
      visible: false,
      form: {
        name: "",
        author: "",
        image: "",
      }
    },
    audio: {
      visible: false,
      form: {
        name: "",
        author: "",
        image: "",
        content: "",
      }
    }
  }),
  computed: {
    currentDir() {
      return this.pathArray[this.pathArray.length - 1]
    },
    user() {
      return isDef(this.$store.state.user) ? this.$store.state.user : null
    },
  },
  mounted() {
    this.fetchDirFiles()
  },
  methods: {
    // 更新当前目录文件
    async fetchDirFiles() {
      const loading = this.$loading()
      try {
        let ret = await fileApi.getAll({parent: this.currentDir.id})
        this.fileList = ret.data.sort((a, b) => a.ext - b.ext)
      } catch (e) {
        this.$msg.danger(e)
      } finally {
        loading.close()
      }
    },
    // 创建文件
    fetchForCreateFile({icon, name, ext, content, author, image}) {
      if (!this.processCheckAccess(this.currentDir)) {
        this.$msg.warning("权限不足")
        return
      }
      const loading = this.$loading()
      fileApi.add({
        icon, name, ext, content, author, image,
        parent: this.currentDir.id,
        createBy: this.user ? this.user.id : null
      }).then(ret => {
        loading.close()
        if (ret.code === 0) {
          this.fetchDirFiles()
          this.$msg.success("添加成功")
        }
      })
    },
    // context添加文本文件
    handleContextAddTextFile() {
      console.log(this.user)
      this.$prompt('请输入文件名', '添加文本文件').then(({value}) => {
        this.fetchForCreateFile({
          icon: "icon-weibiaoti--",
          name: value,
          ext: 2
        })
      })
    },
    // context添加目录
    handleContextAddDirFile() {
      this.$prompt('请输入目录名称', '添加文件夹').then(({value}) => {
        this.fetchForCreateFile({
          icon: "icon-wenjianjia", name: value
        })
      })
    },
    // context添加专辑
    handleContextAddAlbum() {
      this.album.visible = true
    },
    // context添加专辑
    handleContextAddAudio() {
      this.audio.visible = true
    },
    handleAlbumCreate() {
      this.album.visible = false
      this.fetchForCreateFile({
        icon: "icon-ziyuan",
        name: this.album.form.name,
        ext: 3,
        author: this.album.form.author,
        image: this.album.form.image
      })
    },
    handleAudioCreate() {
      this.audio.visible = false
      this.fetchForCreateFile({
        icon: "icon-gequzongliang",
        name: this.audio.form.name,
        ext: 4,
        author: this.audio.form.author,
        image: this.audio.form.image,
        content: this.audio.form.content
      })
    },
    handleAlbumCancel() {
      this.album.visible = false
    },
    // context上传图片
    handleContextAddImgFile() {
      this.dialogVisible = true
    },
    // context重命名文件
    handleContextRenameFile(file) {
      if (this.processCheckAccess(file)) {
        this.$prompt('请输入新的名称', '重命名').then(({value}) => {
          const loading = this.$loading()
          fileApi.update({id: file.id, name: value}).then(ret => {
            if (ret.code === 0) {
              this.$msg.success("Done!")
              this.fetchDirFiles()
            }
          }).finally(() => {
            loading.close()
          })
        })
      } else {
        this.$msg.warning("权限不足")
      }
    },
    handleContextEditFile(file) {
      this.$store.dispatch("openApp", {appID: 1102}).then(() => {
        this.$store.dispatch("sendMsg", {
          from: this, to: 1102,
          data: {
            type: "edit",
            item: file,
            callback: ({value, isBlog, title, tag}) => {
              fileApi.update({id: file.id, content: value, isBlog, title, tag}).then(ret => {
                if (ret.code === 0) {
                  this.$msg.success("保存成功")
                  this.fetchDirFiles()
                }
              })
            }
          }
        })
      })
    },
    // context删除文件
    handleContextDelFile(file) {
      if (!this.processCheckAccess(file)) {
        this.$msg.warning("权限不足")
      } else {
        fileApi.delete(file.id).then(ret => {
          if (ret.code === 0) {
            this.$msg.success("删除成功")
            this.fetchDirFiles()
          }
        })
      }
    },
    // 文件被点击
    handleFileClick(file) {
      let {ext} = file
      if (!ext) {
        this.pathArray.push(file)
        this.fetchDirFiles()
      } else if (ext === 1) {
        // 打开图片浏览器,传递消息
      } else if (ext === 2) {
        // 打开文档浏览器,传递消息
        this.$store.dispatch("openApp", {appID: 1102}).then(() => {
          this.$store.dispatch("sendMsg", {
            from: this,
            to: 1102,
            data: {
              type: "preview",
              item: file
            }
          })
        })
      } else if (ext === 3) {
        // 专辑
        this.pathArray.push(file)
        this.fetchDirFiles()
      } else if(ext === 4){
        // 打开播放器
        this.$store.dispatch("openApp", {appID: 1103}).then(()=>{
          this.$store.dispatch("sendMsg", {
            from: this,
            to: 1103,
            data: {
              album: this.currentDir,
              songID: file.id
            }
          })
        })
      } else {
        this.$msg.warning("系统没有找到处理该文件类型的应用")
      }
    },
    // 返回按钮
    handleBackClick() {
      if (this.pathArray.length > 1) {
        this.pathArray.pop()
        this.fetchDirFiles()
      }
    },
    // 地址栏点击
    handlePathItemClick(index) {
      this.pathArray = this.pathArray.slice(0, index + 1)
      this.fetchDirFiles()
    },
    // 文件区域(非文件)context
    handleContextFilesArea(e) {
      if (e.target === this.$refs.files && this.currentDir.id !== 0) {
        let list = [
          {label: "新建文件夹", click: this.handleContextAddDirFile.bind(this)},
          {label: "新建文本", click: this.handleContextAddTextFile.bind(this)},
          {label: "新建图片", click: this.handleContextAddImgFile.bind(this)},
          {label: "刷新", click: this.fetchDirFiles.bind(this)},
        ]
        // 音乐盘的id
        if (this.currentDir.id === 4) {
          list = [
            {label: "新建专辑", click: this.handleContextAddAlbum.bind(this)},
            {label: "刷新", click: this.fetchDirFiles.bind(this)},
          ]
        }
        // 位于专辑目录
        if(this.currentDir.ext === 3){
          list = [
            {label: "上传歌曲", click: this.handleContextAddAudio.bind(this)},
            {label: "刷新", click: this.fetchDirFiles.bind(this)},
          ]
        }
        this.$store.dispatch("openContext", {
          x: e.x, y: e.y,
          list
        })
      }
    },
    // 文件context
    handleContextFileItem(e, file) {
      let list = [
        {label: "打开", click: this.handleFileClick.bind(this, file)},
        {label: "重命名", click: this.handleContextRenameFile.bind(this, file)},
        {label: "删除", click: this.handleContextDelFile.bind(this, file)},
        {label: "属性", click: this.fetchDirFiles.bind(this)},
      ]
      if (file.ext === 2 && this.processCheckAccess(file)) {
        list.splice(1, 0, {label: "编辑", click: this.handleContextEditFile.bind(this, file)},)
      }
      this.$store.dispatch("openContext", {
        x: e.x, y: e.y,
        list: list
      })
    },
    processUploadSuccess({url, name}) {
      this.fetchForCreateFile({
        icon: "icon-tupian", name, ext: 1, content: url
      })
    },
    processCheckAccess(file) {
      if (file.createBy) {
        if (!this.user) {
          return false
        } else {
          return this.user.role === 'admin' || this.user.id === file.createBy
        }
      } else {
        return true
      }
    }
  },

}
</script>


<style scoped lang="scss">
@import "~@/assets/css/var";

.computer {
  user-select: none;
}

.head {
  .deActive {
    color: $text-place;
  }

  .address-area {
    border: 1px solid $border-1;
    font-size: 12px;

    .path-item {
      cursor: pointer;
      padding: $ps;

      &:hover {
        background-color: rgba(0, 0, 0, 0.1);
      }
    }
  }
}

.files-area {
  position: relative;

  .file-item {
    margin: $mn;
    width: 110px;
    padding: $ps $ps;
    border-radius: 5px;
    height: 80px;

    &:hover {
      background-color: rgba(0, 0, 0, 0.1);
    }

    .name {
      line-height: 1.2;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      word-break: break-all;
      -webkit-line-clamp: 2;
      line-clamp: 2;
      -webkit-box-orient: vertical;
      color: $text-main;
    }
  }

}
</style>
